package club.web51.classroom_tool.Controllers.SystemController;

import club.web51.classroom_tool.Config.UserAuthenticationToken;
import club.web51.classroom_tool.DO.sysDO.Msg;
import club.web51.classroom_tool.DTO.LoginUser;
import club.web51.classroom_tool.DTO.User;
import club.web51.classroom_tool.Enums.MsgEnum;
import club.web51.classroom_tool.Exceptions.ErrDataException;
import club.web51.classroom_tool.Services.UserService;
import club.web51.classroom_tool.Utils.MsgUtil;
import club.web51.classroom_tool.Utils.ObjectUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;

import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @Classname UserController
 * @Description TODO
 * @Date 2020/10/28 20:33
 * @Created by HanYuHao
 */
@CrossOrigin
@Api(value = "用户中心",tags={"用户操作接口"})
@RestController
@RequestMapping("user")
public class UserController {
    @Resource
    UserService userService;

    @GetMapping
    @ApiOperation("查询已经登录的用户信息")
    public Object user_index(){
        Subject currentUser = SecurityUtils.getSubject();
        LoginUser loginUser = (LoginUser) currentUser.getPrincipal();
        return userService.findObjectById(loginUser.getId());
    }

    @PostMapping("login")
    @ApiOperation("用户登录")
    public Msg login(LoginUser loginUser){
        /*
         *
         * 用json传入LoginUser 登录
         */

        User user = new User();
        BeanUtils.copyProperties(loginUser,user);
        Subject currentUser = SecurityUtils.getSubject();
        if(!currentUser.isAuthenticated()){
            if(ObjectUtil.isNull(loginUser)){
                throw new ErrDataException(MsgEnum.ERROR_USER_LOGIN_EXIST.getDescription());
            }
            if(ObjectUtil.isNull(loginUser.getJizhumima())){
                loginUser.setJizhumima(false);
            }
            AuthenticationToken authenticationToken = new UserAuthenticationToken(user,loginUser.getJizhumima());

            currentUser.login(authenticationToken);
        }
            return MsgUtil.success();


    }

    @PostMapping("logout")
    @ApiOperation("用户退出")
    public Msg loginout(){
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return MsgUtil.success();
    }
}
